# -*- coding: utf-8 -*-
import os
import sys
import asyncio
from typing import Optional
from subprocess import Popen, PIPE

from fastapi import FastAPI, BackgroundTasks, Query
from fastapi.responses import JSONResponse

# 切换到项目根，确保 pytest.ini、路径等生效
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
os.chdir(BASE_DIR)

app = FastAPI(title="HOK Interface AutoTest Runner", version="1.0.0")


def run_all_run(scope: str = "web") -> int:
    """同步执行 all_run.py，返回退出码"""
    python_exec = sys.executable
    env = os.environ.copy()
    # 将 scope 传入为环境变量，便于后续扩展（如根据scope在all_run里决定main分支）
    env["HOK_RUN_SCOPE"] = scope
    proc = Popen([python_exec, "all_run.py"], cwd=BASE_DIR, stdout=PIPE, stderr=PIPE, text=True, env=env)
    stdout, stderr = proc.communicate()
    exit_code = proc.returncode
    log_path = os.path.join(BASE_DIR, "current_log.log")
    # 将本次运行的标准输出写入日志末尾，便于排查
    try:
        with open(log_path, "a", encoding="utf-8") as f:
            f.write("\n\n===== API Triggered Run (scope=%s) =====\n" % scope)
            f.write(stdout or "")
            if stderr:
                f.write("\n[stderr]\n" + stderr)
    except Exception:
        pass
    return exit_code


async def run_all_run_async(scope: str = "web") -> int:
    loop = asyncio.get_event_loop()
    return await loop.run_in_executor(None, run_all_run, scope)


@app.post("/run")
async def run(background_tasks: BackgroundTasks, scope: Optional[str] = Query(default="web", regex="^(web|app|c|all)$")):
    """触发一次测试运行。scope: web/app/c/all"""
    background_tasks.add_task(run_all_run_async, scope)
    return JSONResponse({"ok": True, "message": "task accepted", "scope": scope})


@app.get("/health")
async def health():
    return {"status": "ok"}


# 本地启动: uvicorn server:app --host 0.0.0.0 --port 8000



